from typing import TypeVar, List, Generic, Any, Self

from pydantic import Field, model_serializer

from core.utils.pydantic_model import GlobalBaseModel
from core.utils.query_model import QueryModel

T = TypeVar('T')


class QueryPage(GlobalBaseModel, Generic[T]):
    """
    分页查询
    """
    pageIndex: int = Field

    pageSize: int = Field(default=10)

    data: List[T] = Field(default_factory=list)

    totalRow: int = Field(default=1)

    @model_serializer(when_used="json")
    def serialize_model(self) -> dict:
        """
        对于json序列化时，会调用此方法
        :return:
        """
        query_model_dict = super().model_dump()
        query_model_dict.update({"totalPage": self.__total_page()})
        return query_model_dict

    @classmethod
    def create_with_query_model(cls, query: QueryModel[Any], data: List[T], total: int) -> Self:
        """
        类方法创建实例
        """
        return QueryPage[T](pageIndex=query.get_start_row_index(), pageSize=query.pageSize, data=data,
                            totalRow=total)

    @classmethod
    def create_with_data(cls, data: List[T], total: int, page_index: int, page_size: int) -> Self:
        """
        类方法创建实例
        """
        return QueryPage[T](pageIndex=page_index, pageSize=page_size, data=data, totalRow=total)

    def __total_page(self) -> int:
        """
        获取总页数
        """
        if self.pageSize <= 0:
            return 1
        return 1 if self.totalRow == 0 else int(self.totalRow / self.pageSize + (
            1 if self.totalRow % self.pageSize > 0 else 0))
